<template>
  <el-row>
    <div class="category-search">
      <el-form ref="elForm" :model="formData" inline>
        <el-form-item prop="categoryName" label="品类名称：" label-width="100px">
          <el-input
            placeholder="请输入品类名称"
            v-model="formData.categoryName"
            @keyup.enter.native="handleSerachCategory"
          ></el-input>
        </el-form-item>
        <el-form-item prop="categoryName" label="品类编码：" label-width="100px">
          <el-input
            placeholder="请输入四级类编码"
            v-model="formData.categoryNo"
            @keyup.enter.native="handleSerachCategory"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSerachCategory">查询</el-button>
          <el-button type="primary" @click="handleSubmitCategory">确定</el-button>
          <el-button @click="handleCancelCategory">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="category-searchlist">
      <ul>
        <li v-for="(item, index) in searchList.dataSource" :key="index">
          <el-radio
            v-model="searchList.radioValue"
            :label="index"
            @change="(val) => { handleCheckSearchList(val, item) }"
            ><span></span
          ></el-radio>
          {{ item.categoryPath }}&nbsp;&nbsp;{{ item.categoryNoPath }}
        </li>
      </ul>
    </div>
    <div class="category-tree">
      <el-tree
        lazy
        ref="elTree"
        accordion
        show-checkbox
        node-key="categoryUuid"
        :data="elTree.dataSource"
        :load="childTreeDataLoadedFn"
        :props="elTree.defaultProps"
        @check="checkboxClickedFn"
      ></el-tree>
    </div>
  </el-row>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { isResponseSuccess } from '@/utils/bizUtils';
export default {
  data () {
    return {
      formData: { categoryName: '', categoryNo: '' },
      searchList: { // 查询列表
        dataSource: [], // 数据源
        radioValue: -1, // 勾选对象
      },
      elTree: {
        dataSource: [],
        cloneDataSource: [],
        defaultProps: {
          children: 'children',
          label: 'cateNameAndNoStr',
          disabled: 'disabled',
          isLeaf: 'leaf'
        },
        END_LEVEL: '4',
      },
      submitResults: null,
      apiObj: {
        getLevelOneCategoryList: { // 查询一级分类接口
          url: '/sysback/choose/category/getLevelOneCategoryList',
          type: 'post'
        },
        getByParentUuid: { // 根据父分类查询子分类接口
          url: '/sysback/choose/category/getByParentUuid',
          type: 'post'
        },
        getCategoryListByKey: {
          url: '/sysback/choose/category/getCategoryListByKey',
          type: 'post'
        },
        getCategoryClassListByKey: { // form表单查询接口
          url: '/sysback/choose/category/getCategoryListByKey',
          type: 'post'
        }
      }
    }
  },
  mounted () {
    this.getLevelOneCategoryListFn();
  },
  methods: {
    // 表单-分类名称查询
    async handleSerachCategory () {
      const data = {};
      const { categoryNo, categoryName } = this.formData;
      if (!categoryNo && !categoryName) {
        this.$message.warning('品类名称和品类编码不能同时为空');
        return false;
      }
      const { url, type } = this.apiObj.getCategoryListByKey;
      const param = categoryNo ? `categoryNo=${categoryNo}` : `key=${categoryName}`;
      const apiUrl = `${url}?${param}`;
      const res = await ApiRequest(apiUrl, type, data, true);
      if (isResponseSuccess(res)) {
        this.searchList.radioValue = -1;
        this.searchList.dataSource = res.retData;
      }
    },
    // 加载分类子树数据
    childTreeDataLoadedFn (node, resolve) {
      if (node.level === 0) {
        return false;
      }
      const { categoryUuid } = node.data;
      this.getByParentUuidFn(categoryUuid).then(retData => {
        resolve(this.assembleCategoryNodeFn(retData));
      })
    },
    // 点击复选框
    checkboxClickedFn (data) {
      if (this.submitResults && data.categoryUuid === this.submitResults.categoryUuid) {
        this.clearElTreeStateFn();
      } else {
        this.clearSearchRadioStateFn();
        this.$refs.elTree.setCheckedKeys([data.categoryUuid]);
        this.submitResults = this.getSubmitResultsFn(data);
      }
    },
    // 查询一级分类
    async getLevelOneCategoryListFn () {
      const data = {};
      const { url, type } = this.apiObj.getLevelOneCategoryList;
      const res = await ApiRequest(url, type, data, true);
      if (!isResponseSuccess(res)) {
        return false;
      }
      this.elTree.dataSource = this.assembleCategoryNodeFn(res.retData);
    },
    // 根据父分类查询子分类
    async getByParentUuidFn (categoryUuid) {
      const data = {
        parentUuid: categoryUuid,
        categoryType: '01'
      }
      const { url, type } = this.apiObj.getByParentUuid;
      const res = await ApiRequest(url, type, data, true);
      if (!isResponseSuccess(res)) {
        return false;
      }
      return res.retData;
    },
    // 组装分类节点
    assembleCategoryNodeFn (retData) {
      return retData.map(item => {
        const { cateNameAndNoStr, categoryUuid, categoryPath, categoryName, categoryNo, levelNum } = item;
        return {
          cateNameAndNoStr,
          categoryUuid,
          categoryPath,
          categoryName,
          categoryNo,
          levelNum,
          disabled: levelNum !== this.elTree.END_LEVEL,
          leaf: levelNum === this.elTree.END_LEVEL
        }
      })
    },
    // 确定选择分类
    handleSubmitCategory () {
      if (!this.submitResults) {
        this.$message.warning('请选择分类');
        return false;
      }
      this.$emit('submitConcat', this.submitResults);
    },
    // 取消选择分类
    handleCancelCategory () {
      this.$emit('cancelConcat');
    },
    // 选择查询分类列表分类
    handleCheckSearchList (val, data) {
      this.clearElTreeStateFn();
      this.submitResults = this.getSubmitResultsFn(data);
    },
    // 清空分类树的勾选状态和值
    clearElTreeStateFn () {
      this.submitResults = null;
      this.$refs.elTree.setCheckedKeys([]);
    },
    // 清空列表的勾选状态和值
    clearSearchRadioStateFn () {
      this.submitResults = null;
      this.searchList.radioValue = -1;
    },
    // 清空弹框状态值
    clearDialogStateFn () {
      this.$refs.elForm.handleResetForm('formData');
      this.submitResults = null;
      this.searchList.radioValue = -1;
      this.$refs.elTree.setCheckedKeys([]);
    },
    // 获取确定的结果
    getSubmitResultsFn (data) {
      const { categoryUuid, categoryPath, categoryNo } = data;
      return { categoryUuid, categoryPath, categoryNo }
    }
  }
}
</script>
<style lang="less" scoped>
.category-searchlist {
  ul {
    border: 1px solid #ebeef5;
    padding-left: 5px;
    list-style: none;
    max-height: 200px;
    overflow-y: auto;
    li {
      line-height: 24px;
      &:first-child {
        margin-top: 10px;
      }
      &:last-child {
        margin-bottom: 10px;
      }
    }
  }
}
/deep/ .category-tree {
  height: 400px !important;
  overflow: auto;
  margin: 10px 0px;
  border: 1px solid #ebeef5;
}
</style>
